<?php
/**
 * @package common
 */

/**
 * Improved XMLReader which is designed to read specific xml structure.
 */
class XMLReaderEx extends XMLReader {
	/**
	 * Convert codes with design
	 * 	<?xml version="1.0" encoding="UTF-8"?>
	 *		<codes>
	 *	...
	 *		<code id="30002">
	 *			<item lang="cs">Heslo</item>
	 *			<item lang="en">Password</item>
	 *			<item lang="de">Eine passwort</item>
	 *		</code>
	 *		...
	 *	</codes>
	 * to an associative array so that they may be simple readable.
	 * 
	 * @param array $assoc
	 * @return unknown
	 */
	function codes2Assoc(array $assoc = null) {
		if (!isset($assoc))
			$assoc = null;
		while($this->read()) {
			switch ($this->nodeType) {
				case parent::END_ELEMENT:
					// we don't want to return unitialized value when `<smth></smth>' is used
					return isset($assoc) ? $assoc : ''; 
				case parent::ELEMENT:
					$name = $this->name;
					$isempty = $this->isEmptyElement;
					$attr = "";
					if($this->hasAttributes) {
						while($this->moveToNextAttribute()) {
							$attr = $this->value;
						}
					}
					if ($attr == "") {
						$assoc[$name] = $isempty ? '' : self::codes2Assoc(null);
					} else { 
						$assoc[$name][$attr] = $isempty ? '' : self::codes2Assoc(null);
					}
				break;
				case parent::TEXT:
				case parent::CDATA: $assoc .= $this->value;
			}
		}
		return $assoc;		
	}	
}
?>